package jude.java.framework.ajax;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;

/**
 * dwr
 * */
public class BaseAjax {
	
	private WebContext context;
	
	protected WebContext getContext() {
		if (context == null)
			context = WebContextFactory.get();
		return context;
	}
	
	protected HttpServletRequest getRequest() {
		return getContext().getHttpServletRequest();
	}
	
	protected HttpServletResponse getResponse() {
		return getContext().getHttpServletResponse();
	}
	
	protected HttpSession getSession() {
		return getRequest().getSession();
	}
	
	protected String getParameter(String key) {
		return getRequest().getParameter(key);
	}
	
	protected String getParameter(String key, String def) {
		return StringUtils.defaultString(getRequest().getParameter(key), def);
	}
	
	protected ServletContext getServletContext(){
		return WebContextFactory.get().getServletContext();
	}
	
	protected void checkPermission(HttpServletRequest request, String permissionName){
		
	}
	
	protected void checkPermission(HttpServletRequest request, String workNo,String permissionName){
	}
	
	protected void forward(String url) {
		try {
			getContext().forwardToString(url);
			// getContext().getHttpServletRequest().getRequestDispatcher(url).forward(request, getResponse());
			// getContext().getHttpServletResponse().sendRedirect(url);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	protected <T> T execute(AjaxCallback<T> callback) {
		return callback == null ? null : callback.executeInAjax();
	}
}
